/*
 *	Author: Vitaly Rozhkov
 *	vitaly.rozhkov@gmail.com
 *  http://bookvarius.livejournal.com
 *
*/

#include "Batch Helpers/include/common.jsx"

var configFilePath =  app.path.toString() + "/Presets/Scripts/Batch Helpers/config/MakeBorderCfg.txt";
var settings;

function _readSettings(silent){
	settings = ConfigRead(configFilePath);
	if(	null == settings || 
		(!settings['borderHorisontalWidth'].isInteger() || 
		!settings['borderVerticalWidth'].isInteger() )
	)
	{
		if(!silent){
			alert('Use default settings: 1x1');
		}
		if(null == settings){
			settings = new Array();
		}
		settings['borderHorisontalWidth'] = 1;
		settings['borderVerticalWidth'] = 1;
	}
}

function _checkSize(img, silent) {
	if(null == img){
		img = app.activeDocument;
	}
	
	var res = 0;
	if(	settings['borderHorisontalWidth']*2 >= img.height || 
		settings['borderVerticalWidth']*2 >= img.width )
	{
		res = -1;
	}
	return res;
}

function _makeBorder(img, silent) {
	if(null == img){
		img = app.activeDocument;
	}
	var selRegion = Array( 	Array(0+settings['borderVerticalWidth'], 0+settings['borderHorisontalWidth']), 
							Array(img.width-settings['borderVerticalWidth'], 0+settings['borderHorisontalWidth']), 
							Array(img.width-settings['borderVerticalWidth'], img.height-settings['borderHorisontalWidth']), 
							Array(0+settings['borderVerticalWidth'], img.height-settings['borderHorisontalWidth']));
	 
	img.selection.select(selRegion);
	img.selection.invert();
}

/*---------------- interface functions ----------------------*/

function MakeBorder(img, silent){
	if(null == silent){
		silent = 0;
	}
	_readSettings(silent);
	
	var img = app.activeDocument;
	if(0 != _checkSize(img, silent)){
		return -1;
	}

	
	
	return _makeBorder(img, silent);
}




